<template>
  <div class="post-list">
    <h1>帖子列表</h1>
    
    <!-- 登录表单 -->
    <div v-if="!isLoggedIn" class="login-form">
      <h2>登录</h2>
      <form @submit.prevent="handleLogin">
        <input v-model="loginForm.username" type="text" placeholder="用户名" />
        <input v-model="loginForm.password" type="password" placeholder="密码" />
        <button type="submit">登录</button>
      </form>
    </div>

    <!-- 帖子列表 -->
    <div v-else>
      <!-- 发帖表单 -->
      <div class="post-form">
        <h3>发表新帖</h3>
        <form @submit.prevent="handleCreatePost">
          <input v-model="postForm.title" type="text" placeholder="标题" />
          <textarea v-model="postForm.content" placeholder="内容"></textarea>
          <button type="submit">发表</button>
        </form>
      </div>

      <div v-if="loading">加载中...</div>
      <div v-else class="posts">
        <div v-for="post in posts" :key="post.id" class="post-item">
          <h2>{{ post.title }}</h2>
          <p>{{ post.content }}</p>
          <div class="post-meta">
            <span>作者: {{ post.author.username }}</span>
            <span>浏览: {{ post.viewCount }}</span>
            <span>
              <button @click="handleLike(post)">
                {{ post.isLiked ? '取消点赞' : '点赞' }} ({{ post.likeCount }})
              </button>
            </span>
          </div>
          
          <!-- 评论区 -->
          <div class="comment-section">
            <h3>评论</h3>
            <form @submit.prevent="handleComment(post.id)">
              <textarea v-model="commentForm[post.id]" placeholder="写下你的评论..."></textarea>
              <button type="submit">发表评论</button>
            </form>
            <div class="comments">
              <div v-for="comment in post.comments" :key="comment.id" class="comment-item">
                <p>{{ comment.content }}</p>
                <div class="comment-meta">
                  <span>{{ comment.author.username }}</span>
                  <span>{{ new Date(comment.createTime).toLocaleString() }}</span>
                  <button v-if="comment.author.id === userInfo?.id" @click="handleDeleteComment(post.id, comment.id)">
                    删除
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import { BbsApi, Post, UserInfo } from '../src';

const api = new BbsApi({
  baseURL: 'http://localhost:3000',
});

export default defineComponent({
  name: 'PostList',
  setup() {
    const posts = ref<Post[]>([]);
    const loading = ref(false);
    const isLoggedIn = ref(false);
    const userInfo = ref<UserInfo | null>(null);

    // 表单数据
    const loginForm = ref({ username: '', password: '' });
    const postForm = ref({ title: '', content: '' });
    const commentForm = ref<Record<number, string>>({});

    // 登录
    const handleLogin = async () => {
      try {
        const response = await api.user.login(loginForm.value.username, loginForm.value.password);
        localStorage.setItem('userToken', response.data.token);
        userInfo.value = response.data.userInfo;
        isLoggedIn.value = true;
        fetchPosts();
      } catch (error) {
        console.error('登录失败:', error);
      }
    };

    // 获取帖子列表
    const fetchPosts = async () => {
      loading.value = true;
      try {
        const response = await api.post.getPosts({
          page: 1,
          pageSize: 10,
        });
        posts.value = response.data.list.map(post => ({
          ...post,
          comments: [],
          isLiked: false
        }));
        // 获取每个帖子的评论
        for (const post of posts.value) {
          const commentsResponse = await api.comment.getComments(post.id, {
            page: 1,
            pageSize: 5,
          });
          post.comments = commentsResponse.data.list;
        }
      } catch (error) {
        console.error('获取帖子列表失败:', error);
      } finally {
        loading.value = false;
      }
    };

    // 发表帖子
    const handleCreatePost = async () => {
      try {
        await api.post.createPost(postForm.value);
        postForm.value = { title: '', content: '' };
        fetchPosts();
      } catch (error) {
        console.error('发表帖子失败:', error);
      }
    };

    // 点赞/取消点赞
    const handleLike = async (post: Post & { isLiked: boolean }) => {
      try {
        if (post.isLiked) {
          await api.post.unlikePost(post.id);
          post.likeCount--;
        } else {
          await api.post.likePost(post.id);
          post.likeCount++;
        }
        post.isLiked = !post.isLiked;
      } catch (error) {
        console.error('操作失败:', error);
      }
    };

    // 发表评论
    const handleComment = async (postId: number) => {
      const content = commentForm.value[postId];
      if (!content?.trim()) return;

      try {
        const response = await api.comment.createComment(postId, content);
        const post = posts.value.find(p => p.id === postId);
        if (post) {
          post.comments.unshift(response.data);
        }
        commentForm.value[postId] = '';
      } catch (error) {
        console.error('发表评论失败:', error);
      }
    };

    // 删除评论
    const handleDeleteComment = async (postId: number, commentId: number) => {
      try {
        await api.comment.deleteComment(postId, commentId);
        const post = posts.value.find(p => p.id === postId);
        if (post) {
          post.comments = post.comments.filter(c => c.id !== commentId);
        }
      } catch (error) {
        console.error('删除评论失败:', error);
      }
    };

    onMounted(() => {
      const token = localStorage.getItem('userToken');
      if (token) {
        isLoggedIn.value = true;
        api.user.getUserInfo().then(response => {
          userInfo.value = response.data;
        });
        fetchPosts();
      }
    });

    return {
      posts,
      loading,
      isLoggedIn,
      userInfo,
      loginForm,
      postForm,
      commentForm,
      handleLogin,
      handleCreatePost,
      handleLike,
      handleComment,
      handleDeleteComment,
    };
  },
});
</script>

<style scoped>
.post-list {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.login-form,
.post-form {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.post-item {
  border: 1px solid #eee;
  margin-bottom: 20px;
  padding: 15px;
  border-radius: 4px;
}

.post-meta,
.comment-meta {
  display: flex;
  gap: 20px;
  color: #666;
  font-size: 14px;
  margin-top: 10px;
}

.comment-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.comment-item {
  padding: 10px;
  border-bottom: 1px solid #eee;
}

input,
textarea {
  width: 100%;
  margin-bottom: 10px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

textarea {
  min-height: 100px;
  resize: vertical;
}

button {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}
</style> 